<template>
  <el-dialog
    title='修改企业基本信息'
    :visible.sync='state'
    :modal-append-to-body='false'
    :close-on-click-modal='false'
    :close-on-press-escape='false'
    @close='closeBox'>
    <el-form :model='form' :rules='rules' ref='form' size='small' label-position='right' label-width='160px'>
      <el-divider content-position='left'><h1>基本信息</h1></el-divider>
      <el-row type='flex' class='row-bg' justify='space-between'  align='middle'>
        <el-col :span='11' class='grid-content'>
          <el-form-item
            label='企业名称：'
            :label-width='formLabelWidth'
            prop='name'>
            <el-input size='small' v-model='form.name' autocomplete='off'></el-input>
          </el-form-item>
        </el-col>

        <el-col :span='12' class='grid-content'>
          <el-form-item
            label='法人代表：'
            :label-width='formLabelWidth'
            prop='legalRepresentative'>
            <el-input size='small' v-model='form.legalRepresentative' autocomplete='off'></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row type='flex' class='row-bg' justify='space-between'>
        <el-col :span='11' class='grid-content'>
          <el-form-item
            label='注册地址：'
            :label-width='formLabelWidth'
            prop='registeredAddress'>
            <el-input size='small' v-model='form.registeredAddress' autocomplete='off'></el-input>
          </el-form-item>
        </el-col>
        <el-col :span='12' class='grid-content'>
          <el-form-item
            label='注册资本：'
            :label-width='formLabelWidth'
            prop='registeredCapital'>
            <el-input size='small' v-model='form.registeredCapital' autocomplete='off'></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row type='flex' class='row-bg' justify='space-between'>
        <el-col :span='11' class='grid-content'>
          <el-form-item
            label='成立时间：'
            :label-width='formLabelWidth'
            prop='buildTime'>
            <el-date-picker
              style='width: 100%'
              v-model='form.buildTime'
              type='date'
              placeholder='选择成立时间'>
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span='12' class='grid-content'>
          <el-form-item
            label='经营状态：'
            :label-width='formLabelWidth'
            prop='operatingStatus'>
            <el-input size='small' v-model='form.operatingStatus' autocomplete='off'></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row type='flex' class='row-bg' justify='space-between'>
        <el-col :span='10' class='grid-content'>
          <el-form-item
            label='企业类别：'
            :label-width='formLabelWidth'
            prop='type'>
            <el-radio-group v-model='form.type'>
              <el-radio :label='1'>一般企业</el-radio>
              <el-radio :label='2'>重点企业</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span='12' class='grid-content'>
          <el-form-item label='经营范围：' :label-width='formLabelWidth' prop='natureBusiness'>
            <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 4}" placeholder="请输入内容" v-model="form.natureBusiness"></el-input>
            <!-- <el-input size='small' v-model='form.natureBusiness' autocomplete='off'></el-input> -->
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="38" type='flex' class='row-bg' justify='start'>
        <el-col :span='12' class='grid-content'>
          <el-form-item
            label='统一社会信用代码:'
            prop='uscc'>
            <el-input size='small' v-model='form.uscc' autocomplete='off'></el-input>
          </el-form-item>
        </el-col>
        <el-col :span='12' class='grid-content'>
          <el-form-item
            label='环保负责人：'
            :label-width='formLabelWidth'
            prop='envPerson'>
            <el-input  size='small' v-model='form.envPerson' autocomplete='off'></el-input>
          </el-form-item>
        </el-col>

      </el-row>

      <el-row type='flex' class='row-bg' justify='space-between'>
        <el-col :span='12' class='grid-content'>
         <el-form-item
           label='国民经济行业类别：'
           prop='industry'>
           <el-cascader  style='width: 100%' v-model='form.industry' ref='cascaderAddr' filterable clearable placeholder='试试搜索：农业' :options='options'></el-cascader>
         </el-form-item>
       </el-col>
        <el-col :span='13' class='grid-content'>
          <el-form-item
            label='环保负责人电话：'
            prop='envPersonPhone'>
            <el-input size='small' v-model='form.envPersonPhone' :maxlength='11' autocomplete='off'></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row type='flex' class='row-bg' justify='start'>
        <el-col :span='11' class='grid-content'>
          <el-form-item
            label-width='120px'
            label='企业执照：'
            prop='uscc'>
            <el-upload
              class='oss-upload' ref='upload' action=''
              :multiple='false'
              :show-file-list='false'
              :on-remove='handleRemove'
              :on-change='handleChange'
              :auto-upload='false'>
              <el-button slot='trigger' size='small' type='primary'>选取文件</el-button>
              <el-button slot='trigger' size='small' type='primary' @click="download(imageUrl)">下载</el-button>
              <img v-if='imageUrl' :src='imageUrl' class='avatar'>
              <!-- <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button> -->
              <!-- <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div> -->
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row type='flex' class='row-bg' justify='space-between' align='middle'>
        <el-col :span='6' class='grid-content'>
          <el-form-item
            label-width='120px'
            label='企业地址：'
            prop='detailedAddress'>
            <el-button type='primary' @click='mapVisible = true'>请选择</el-button>
            <CoordinateMap v-if='mapVisible' @getLnglat='getLnglat'></CoordinateMap>
          </el-form-item>
        </el-col>

        <el-col :span='10' class='grid-content'>
          <el-input v-model='form.address' autocomplete='off'></el-input>
        </el-col>
        <el-col :span='4' class='grid-content'>
          <el-input v-model='form.longitude' autocomplete='off'></el-input>
        </el-col>
        <el-col :span='4' class='grid-content'>
          <el-input v-model='form.latitude' autocomplete='off'></el-input>
        </el-col>
      </el-row>

      <el-divider></el-divider>
      <el-row justify='end' align='middle'>
        <el-col :span='24'>
          <el-form-item style='float: right'>
            <el-button @click="cancel('form')">取 消</el-button>
            <el-button type='primary' @click="submit('form')">确 定</el-button>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- <div style='text-align: right'>
        <el-form-item >
          <el-button @click="cancel('form')">取 消</el-button>
          <el-button type='primary' @click="submit('form')">确 定</el-button>
        </el-form-item>
      </div> -->

    </el-form>
  </el-dialog>
</template>
<script>

import CoordinateMap from '@/components/map/CoordinateMap';

export default {
  components: {
    CoordinateMap,
  },
  computed: {},
  props: ['editItem'],
  data() {
    return {
      formLabelWidth: '120px',
      state: true,

      options: [],

      mapVisible: false,

      imageUrl: '',
      sigData: null,

      form: {
        name: '',
        registeredAddress: '',
        legalRepresentative: '',
        registeredCapital: '',
        buildTime: '',
        operatingStatus: '',
        operatingPeriod: '',
        natureBusiness: '',
        uscc: '',
        businessLicenseAtt: '',
        envPerson: '',
        envPersonPhone: '',
        type: 1,
        industry: '',
        logo: '',

        address: '',
        longitude: '',
        latitude: '',

      },
      rules: {
        name: [{ required: true, message: '请输入企业名称', trigger: 'blur' }],
        registeredAddress: [{ required: true, message: '请输入注册地址', trigger: 'blur' }],
        legalRepresentative: [{ required: true, message: '请输入法人代表', trigger: 'blur' }],
        registeredCapital: [{ required: true, message: '请输入注册资本', trigger: 'blur' }],
        buildTime: [{ type: 'date', required: true, message: '请选择成立时间', trigger: 'change' }],
        operatingStatus: [{ required: true, message: '请输入经营状态', trigger: 'blur' }],
        operatingPeriod: [{ required: true, message: '请输入经营期限', trigger: 'blur' }],
        natureBusiness: [{ required: true, message: '请输入经营范围', trigger: 'blur' }],
        uscc: [{ required: true, message: '请输入统一社会信用代码', trigger: 'blur' }],
        businessLicenseAtt: [{ required: true, message: '请上传营业执照', trigger: 'blur' }],
        envPerson: [{ required: true, message: '请输入环保负责人', trigger: 'blur' }],
        envPersonPhone: [{ required: true, message: '请输入环保负责人电话', trigger: 'blur' }],
        industry: [{ required: true, message: '请选择国民经济行业类', trigger: 'change' }],
        type: [{ required: true, message: '请选择企业类别', trigger: 'change' }],
      },
    };
  },
  created() {
    this.getInfo();
    this.options = this.$INDUSTRY;
    this.getSig();
  },
  mounted() {},
  methods: {
    download(row) {
      window.open(row, "_blank")
      // this.downloadFile(row.path,row.path);
    },
    closeBox() {
      this.state = false;
      this.$ge.$emit('biz-company-change-search');
    },
    cancel(formName) {
      this.state = false;
      this.$refs[formName].resetFields();
    },
    handleRemove(file, fileList) {
      this.form.businessLicenseAtt = '';
    },
    handleChange(file, fileList) {
      //类型（jpg, png）和大小(2M 以内)
      // const isJPG = file.raw.type === 'image/jpeg' || file.raw.type === 'image/png';
      const isLt2M = file.raw.size / 1024 / 1024 < 500;
      // if (!isJPG) {
      //     this.$message.error('上传头像图片只能是 jpg 或者 png 格式!');
      //     return;
      // }
      if (!isLt2M) {
        this.$message.error('单个文件大小不能超过 500MB!');
        return;
      }
      // if(isJPG && isLt2M) {
      //   this.fileList.push(file);
      // }
      this.imageUrl = URL.createObjectURL(file.raw)
      this.form.businessLicenseAtt = file;
      return false;
    },
    // 获取地址信息
    getLnglat(lnglnt) {
      this.mapVisible = false;
      if (!lnglnt) return;
      this.form.longitude = lnglnt.lng
      this.form.latitude = lnglnt.lat
      this.form.address = lnglnt.adr
    },
    getInfo() {
      let that = this;
      this.$get('/biz-company/info', {id: this.editItem.id})
        .then((result) => {
          if (result.code == 200 && result.data) {
              that.form = Object.assign({}, that.form, result.data);
              //联级数据
              if(that.form.industry) {
                that.form.industry = that.form.industry.split(',');
              }
              //营业执照
              if(that.form.businessLicenseAtt) {
                that.imageUrl = that.form.businessLicenseAtt.url;
              }
              if(that.form.buildTime) {
                that.form.buildTime = new Date(that.form.buildTime);
              }
          }
        })
        .catch((error) => {
        });
    },
    getSig() {
      this.$get('/oss/getUploadOssSignature')
        .then((result) => {
          if (result.code == 200 && result.data) {
            this.sigData = result.data;
          }
        })
        .catch((error) => {
          this.sigData = null;
        });
    },
    submit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$WLoading();
          this.submitUpload();
          var param = {};
          param = Object.assign({}, this.form, param);

          //获取国民经济行业类文本
          param.industryText = this.$refs['cascaderAddr'].getCheckedNodes()[0].pathLabels.join('/')
          param.industry = param.industry.join(',')

          this.$postJson('/biz-company/update', param)
            .then((result) => {
              if (result.code == 200) {
                this.$message.success(result.msg);

                //关闭弹框并刷新列表
                this.closeBox(formName);
              } else this.$message.error(result.msg);
              this.$cancelLoading();
            })
            .catch((error) => {
              //添加用户异常
              this.$message.error('添加失败');
              this.$cancelLoading();
            });
        } else {
          return false;
        }
      });
    },
    formatWaste(textStr, type, wasteList) {
      let newStr = '';
      if (textStr.indexOf('，') != -1) {  //寻找每一个中文逗号，并替换
        newStr = textStr.replace(/，/ig, ',');
      }

      let textList = newStr.split(',');
      textList.forEach(element => {
        wasteList.push({
            name: element,
            type: type,
          },
        )
      });
    },
    submitUpload() {
      let fileObj = this.form.businessLicenseAtt;
      let sigData = this.sigData;//提前请求拿到的签名信息
      const element = fileObj;
      if(!element.raw) {
        return false;
      }
      let ossData = new FormData()//创建oss数据对象
      ossData.append('name', element.name)
      let keyValue = 'ep/web/' + this.uuid() + '::' + element.name
      ossData.append('key', keyValue)
      ossData.append('policy', sigData.policy)
      ossData.append('OSSAccessKeyId', sigData.accessId)
      ossData.append('success_action_status', 200)
      ossData.append('Signature', sigData.signature)
      ossData.append('file', element.raw)

      this.$postFormData(sigData.ossDomain, ossData)
        .then((result) => {
          // console.log('上传结束 -- ', result)
        })
        .catch((error) => {
        });

      this.form.businessLicenseAtt = {
        name: element.name,
        url: sigData.ossDomain +'/'+ keyValue,
        size: element.size,
      }
      // this.$message.success("文件上传成功！");
    },

  },
};
</script>

<style scoped>
.el-select {
  width: 100%;
}

.vue-treeselect__input {
  border: 0 !important;
}



/* 上传样式 start */
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.el-divider__text{
  padding: 0;
}


.el-form-item--mini.el-form-item, .el-form-item--small.el-form-item{
  margin: 0;
}


.el-divider--horizontal{
  margin: 40px 0;
}

.el-row{
 text-align: left;
}

.el-row--flex{
  margin:15px 0
}

/* 上传样式 end */
</style>
